package com.thinkingcoder.tcmq.demo;

import com.alibaba.fastjson.JSON;
import com.thinkingcoder.tcmq.client.TcBroker;
import com.thinkingcoder.tcmq.client.TcConsumer;
import com.thinkingcoder.tcmq.client.TcProducer;
import com.thinkingcoder.tcmq.core.model.Message;

import lombok.SneakyThrows;

public class TcMqDemo {

    @SneakyThrows
    public static void main(String[] args) {

        long ids = 0;

        String topic = "com.thinkingcoder.tcmq.test";
        TcBroker broker = new TcBroker();

        TcProducer producer = broker.createProducer();
        // TcConsumer<?> consumer = broker.createConsumer(topic);
        // consumer.subscribe(topic);
        // consumer.listen(topic, message -> {
        // System.out.println(" onMessage => " + message); // 这里处理消息
        // });

        TcConsumer<?> consumer = broker.createConsumer(topic);

        for (int i = 0; i < 10; i++) {
            Order order = new Order(ids, "item" + ids, 100 * ids);
            producer.send(topic, new Message<>((long)ids++, JSON.toJSONString(order), null));
        }

        for (int i = 0; i < 10; i++) {
            Message<String> message = (Message<String>)consumer.receive(topic);
            System.out.println(message);
            consumer.ack(topic, message);
        }

        while (true) {
            char c = (char)System.in.read();
            if (c == 'q' || c == 'e') {
                break;
            }
            if (c == 'p') {
                Order order = new Order(ids, "item" + ids, 100 * ids);
                producer.send(topic, new Message(ids++, JSON.toJSONString(order), null));
                System.out.println("produce ok => " + order);
            }
            if (c == 'c') {
                // Message<Order> message = (Message<Order>)consumer.receive(topic);
                // System.out.println("poll ok => " + message);
            }
            if (c == 'a') {
                for (int i = 0; i < 10; i++) {
                    Order order = new Order(ids, "item" + ids, 100 * ids);
                    producer.send(topic, new Message<>((long)ids++, JSON.toJSONString(order), null));
                }
                System.out.println("produce 10 orders...");
            }
        }
    }

}
